import {getLyric} from 'api/song'
import {ERR_OK} from 'api/config'
import {Base64} from 'js-base64'
// import axios from 'axios'

export default class Song {
  constructor ({id, mid, singer, name, album, duration, image, url}) {
    this.id = id
    this.mid = mid
    this.singer = singer
    this.name = name
    this.album = album
    this.duration = duration
    this.image = image
    this.url = url
  }
  getLyric () {
    if (this.lyric) {                                // 判断就可以只执行一次请求，优化代码
      return Promise.resolve(this.lyric)
    }

    return new Promise((resolve, reject) => {
      getLyric(this.mid).then((res) => {
        if (res.retcode === ERR_OK) {
          this.lyric = Base64.decode(res.lyric)
          resolve(this.lyric)
        } else {
          reject('no lyric')
        }
      })
    })
  }
}

export function createSong (musicData, vkey) {
  return new Song({
    id: musicData.id || musicData.songid,
    mid: musicData.mid || musicData.songmid,
    singer: musicData.singer[0].name,
    name: musicData.name || musicData.songname,
    album: musicData.album ? musicData.album.name : musicData.albumname,
    duration: musicData.interval,
    // image: `http://imgcache.qq.com/music/photo/album_300/20/300_albumpic_140820_0.jpg`,
    image: `https://y.gtimg.cn/music/photo_new/T002R300x300M000${musicData.album ? musicData.album.mid : musicData.albummid}.jpg?max_age=2592000`,
    url: `http://dl.stream.qqmusic.qq.com/C400${musicData.mid || musicData.songmid}.m4a?fromtag=38&guid=5931742855&vkey=${vkey}`
  })
}

// function filterSinger (singer) {
//   let ret = []
//   if (!singer) {
//     return ''
//   }
//   singer.forEach((s) => {
//     ret.push(s.name)
//   })
//   return ret.join('/')
// }

